<?php

class IngatlanController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'eladoView', 'berelhetoView', 'cserelhetoView', 'teszt'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $model = $this->loadModel($id);
        $model->setIngatlanTipusNev();
        $model->setVarosNev();

        $this->render('view', array(
            'model' => $model,
        ));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Ingatlan');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Ingatlan::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'ingatlan-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Adott ingatlan típusú ingatlanokat listáz ki. (Eladó)
     * @param type $ingatlan_tipus_ID milyen típusú ingatlanokat listázzuk ki
     */
    public function actionEladoView($ingatlan_tipus_ID) {
        //breadcrumbs
        $ingatlanTipusNev = IngatlanTipus::model()->findByPk($ingatlan_tipus_ID);

        $crit = new CDbCriteria();
        $crit->addCondition('ingatlan_tipus_ID=' . $ingatlan_tipus_ID);
        $crit->join = 'INNER JOIN ingatlan_has_ingatlan_kategoria ON ingatlan_has_ingatlan_kategoria.ingatlan_ID = ID';
        $crit->join .= ' INNER JOIN ingatlan_kategoria ON ingatlan_kategoria.ID = ingatlan_has_ingatlan_kategoria.ingatlan_kategoria_ID';
        $crit->addCondition("ingatlan_kategoria.kategoria_nev = 'Eladó'");

        $dataProvider = new CActiveDataProvider('Ingatlan', array(
            'criteria' => $crit,
                ));

        $this->render('index', array(
            'dataProvider' => $dataProvider,
            'ingatlanTipusNev' => $ingatlanTipusNev->tipus_nev,
            'kategoria' => 'Eladó',
        ));
    }

    /**
     * Bérelhető ingatalnokat listázza ki. (Bérelhető)
     * @param type $ingatlan_tipus_ID milyen típusú ingatlanokat listázzuk ki
     */
    public function actionBerelhetoView() {

        $crit = new CDbCriteria();
        $crit->join = 'INNER JOIN ingatlan_has_ingatlan_kategoria ON ingatlan_has_ingatlan_kategoria.ingatlan_ID = ID';
        $crit->join .= ' INNER JOIN ingatlan_kategoria ON ingatlan_kategoria.ID = ingatlan_has_ingatlan_kategoria.ingatlan_kategoria_ID';
        $crit->addCondition("ingatlan_kategoria.kategoria_nev = 'Bérelhető'");

        $dataProvider = new CActiveDataProvider('Ingatlan', array(
            'criteria' => $crit,
                ));

        $this->render('index', array(
            'dataProvider' => $dataProvider,
            'kategoria' => 'Bérelhető',
        ));
    }

    /**
     * Cserélhető ingatlanokat listázza ki. (Cserélhető)
     * @param type $ingatlan_tipus_ID milyen típusú ingatlanokat listázzuk ki
     */
    public function actionCserelhetoView() {

        $crit = new CDbCriteria();
        $crit->join = 'INNER JOIN ingatlan_has_ingatlan_kategoria ON ingatlan_has_ingatlan_kategoria.ingatlan_ID = ID';
        $crit->join .= ' INNER JOIN ingatlan_kategoria ON ingatlan_kategoria.ID = ingatlan_has_ingatlan_kategoria.ingatlan_kategoria_ID';
        $crit->addCondition("ingatlan_kategoria.kategoria_nev = 'Cserélhető'");

        $dataProvider = new CActiveDataProvider('Ingatlan', array(
            'criteria' => $crit,
                ));

        $this->render('index', array(
            'dataProvider' => $dataProvider,
            'kategoria' => 'Cserélhető',
        ));
    }

    /**
     * Joomla adatbázis migráció
     */
    public function actionAdatbazisMigracio() {
        $model = Yii::app()->dbTest->createCommand()
                ->select('*, loc.name varos_nev, t.id t_id, pr.cid category_id')
                ->from('jos_properties_products pr,
                        jos_properties_product_category prhc,
                        jos_properties_category cat,
                        jos_properties_type t,
                        jos_properties_country country,
                        jos_properties_locality loc,
                        jos_properties_state state')
                ->where('pr.id = prhc.productid
                        AND prhc.categoryid = cat.id
                        AND pr.lid = loc.id
                        AND pr.sid = state.id
                        AND pr.cyid = country.id
                        AND pr.type = t.id')
                ->query();

        foreach ($model as $row) {
            $ingatlan = new Ingatlan();
            //$ingatlan->ID = $row['id'];
            $ingatlan->publikus = $row['published'];
            $ingatlan->iranyitoszam = $row['postcode'];
            $ingatlan->ar = $row['price'];
            $ingatlan->leiras = $row['description'];
            $ingatlan->ingatlan_tipus_ID = $row['t_id'];

            $varos = Varos::model()->find("varos_nev='" . $row['varos_nev'] . "'");
            //13. kerület kezelése
            if ($varos != null)
                $ingatlan->varos_ID = $varos->ID;
            else
                $ingatlan->varos_ID = '3239';
            $ingatlan->insert();

            $ingatlan_kategoria = new IngatlanHasIngatlanKategoria();
            $ingatlan_kategoria->ingatlan_ID = $ingatlan->ID;
            $ingatlan_kategoria->ingatlan_kategoria_ID = $row['category_id'];
            $ingatlan_kategoria->insert();
        }
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Ingatlan('search');
        $model->unsetAttributes();  // clear any default values


        if (isset($_GET['Ingatlan']))
            $model->attributes = $_GET['Ingatlan'];


        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['ing_kat'])) {
            
            $model->ingatlan_tipus_ID = $_POST['ing_tip'];
            $model->varos_ID = $_POST['varos'];
            $model->publikus = $_POST['public'];
            $model->eladva = $_POST['eladva'];
            $model->cim = $_POST['cim'];
            $model->iranyitoszam = $_POST['iranyitoszam'];
            $model->ar = $_POST['ar'];
            $model->leiras = $_POST['leiras'];
            
            $model->update();
            
            //ingatlan kategória mentése
            $ing_kat = IngatlanHasIngatlanKategoria::model()->find('ingatlan_ID = '.$id);
            $ing_kat->ingatlan_kategoria_ID = $_POST['ing_kat'];
            $ing_kat->update();
            
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Ingatlan;
        $model->varos_ID = null;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['ing_kat'])) {
            
            $model->ingatlan_tipus_ID = $_POST['ing_tip'];
            $model->varos_ID = $_POST['varos'];
            $model->publikus = $_POST['public'];
            $model->eladva = $_POST['eladva'];
            $model->cim = $_POST['cim'];
            $model->iranyitoszam = $_POST['iranyitoszam'];
            $model->ar = $_POST['ar'];
            $model->leiras = $_POST['leiras'];
            
            $model->insert();
            
            //ingatlan kategória mentése
            $ing_kat = new IngatlanHasIngatlanKategoria;
            $ing_kat->ingatlan_ID = $model->ID;
            $ing_kat->ingatlan_kategoria_ID = $_POST['ing_kat'];
            $ing_kat->insert();
            
            //ingatlan jellemzok mentése
            foreach ($_POST['Ingatlan']['ID'] as $value) {
                $ing_kat = new IngatlanHasIngatlanJellemzo;
                $ing_kat->ingatlan_ID = $model->ID;
                $ing_kat->ingatlan_jellmzo_ID = $value;
                $ing_kat->insert();
            }
            
            
            
        }


        


        $this->render('create', array(
            'model' => $model
        ));
    }

    
    
    
}
